package com.atguigu.jinx.service.impl;



import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static com.atguigu.jinx.utils.NameConstants.TENCENT_COS_PICTURE_FIXED_NAME;

@Service
public class TencentCosService {

    private final COSClient cosClient;

    @Value("${tencent.cos.bucketName}")
    private String bucketName;

    @Value("${tencent.cos.urlPrefix}")
    private String urlPrefix;

    public TencentCosService(COSClient cosClient) {
        this.cosClient = cosClient;
    }

    // 上传本地文件
    public String uploadFile(String filePath, String fileName) {
        File localFile = new File(filePath);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, localFile);
        PutObjectResult result = cosClient.putObject(putObjectRequest);
        return urlPrefix + fileName;
    }

    // 上传 MultipartFile（前端传来的文件）
    public String uploadMultipartFile(MultipartFile file, String fileName) throws IOException {
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.getSize());
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName,
                file.getInputStream(), metadata);
        cosClient.putObject(putObjectRequest);
        return urlPrefix + fileName;
    }

    /**
     * 删除文件
      */

    public void deleteFile(List<String> fileNames) {
        // 处理
        for (String s : fileNames.stream().map(
                deleteFileUrl -> {
                    String[] parts = deleteFileUrl.split("images/");
                    String result = "" ;
                    if (parts.length > 1) {
                          result = "images/" + parts[1];
                    }
                    return result;
                }
        ).toList()) {
            cosClient.deleteObject(bucketName, s);
        }

    }

    public List<String> getFiles(){
        ObjectListing objectListing = cosClient.listObjects(bucketName);
        List<COSObjectSummary> objectSummaries = objectListing.getObjectSummaries();
        // 遍历图片集合 => 查找该图片在数据库中是否存在? 删除:保留

        if (CollectionUtils.isEmpty(objectSummaries)){
            return Collections.emptyList();
        }
        return objectSummaries.stream().map(objectSummary -> {
            // 拼接完整路径 TODO 是否有更好的解决办法?
            return objectSummary.getBucketName()
                    .concat(TENCENT_COS_PICTURE_FIXED_NAME)
                    .concat(objectSummary.getKey());
        }).collect(Collectors.toList());

    }
}
